//
//  BHHtmlContentWebCell.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/8/10.
//

import UIKit
import WebKit

class BHHtmlContentWebCell: UITableViewCell {
    
    var webCellCallRealHeightBlock:((CGFloat) -> Void)?
    
    
    lazy var webView: WKWebView = {
        let conf = WKWebViewConfiguration()
        let userContent = WKUserContentController.init()
        
        conf.userContentController = userContent
        conf.preferences.javaScriptEnabled = true
        conf.selectionGranularity = WKSelectionGranularity.character
        conf.allowsInlineMediaPlayback = true
   
        let web = WKWebView.init()
        web.uiDelegate = self
        web.scrollView.isScrollEnabled = false
        web.scrollView.bounces = false
        web.navigationDelegate = self
        web.scrollView.delegate = self
        web.scrollView.contentInsetAdjustmentBehavior = .never
        return web
    }()
    deinit {
        observation = nil
    }

    // 需要被 observer 持有, 会随持有者被释放
    var observation: NSKeyValueObservation?
    
    var htmlText: String = "" {
        didSet {
           
            self.webView.loadHTMLString(htmlText, baseURL: nil)
            
            self.observerAndUpdateWebViewHeight()
        }
    }
    
    // 监听网页滚动区域变化
    private func observerAndUpdateWebViewHeight() {
        
        observation = self.webView.scrollView.observe(\UIScrollView.contentSize, options: [.new]) { [weak self] (_, change) in
               
            guard let self = self else { return }
               // 直接获取新值
            let webH = change.newValue?.height ?? 0
//            let webH = CGFloat(1672.5)
            
            self.webCellCallRealHeightBlock?(CGFloat(webH))
            self.webView.frame = CGRect(x: 5, y: 0, width: UIScreen.width-10, height: webH)
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.contentView.addSubview(self.webView)
        self.webView.frame = CGRect(x: 5, y: 0, width: UIScreen.width-10, height: 1)
        self.clipsToBounds = true
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        
    }
}
extension BHHtmlContentWebCell: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return nil
    }
}

extension BHHtmlContentWebCell: WKUIDelegate,WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        //  长按事件禁用
        webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';document.documentElement.style.webkitUserSelect='none';", completionHandler: nil)
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        // html页面与屏幕宽度不符问题
        webView.evaluateJavaScript("""
             var oMeta = document.createElement('meta');
             oMeta.content = 'width=device-width, initial-scale=1, user-scalable=0';
             oMeta.name = 'viewport';
             document.getElementsByTagName('head')[0].appendChild(oMeta);
             """,completionHandler: nil)


        // 图片缩放比例不正确问题
     
        webView.evaluateJavaScript("""
                var imgs = document.getElementsByTagName(\"img")
                for (var i = 0; i < imgs.length; i++) {
                    imgs[i].setAttribute('width', '100%')
                }
                """,completionHandler: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
           let alertCtrl = UIAlertController(title: "温馨提示", message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: "确定", style: .default) { (action) in
            completionHandler()
           
        }
        alertCtrl.addAction(action)
        
        BHNavigationController.currentNavigationController!.present(alertCtrl, animated: true, completion: nil)
    }
    
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        
          let alertCtrl = UIAlertController(title: "温馨提示", message: message, preferredStyle: .alert)
          let okAction = UIAlertAction(title: "确定", style: .default) { (action) in
              completionHandler(true)
          }
          let cancelAction = UIAlertAction(title: "取消", style: .default) { (action) in
              completionHandler(false)
          }
          alertCtrl.addAction(okAction)
          alertCtrl.addAction(cancelAction)
        BHNavigationController.currentNavigationController!.present(alertCtrl, animated: true, completion: nil)

    }
    
}
